﻿Imports System.Windows.Media.Animation
Imports System.Diagnostics
Imports System.Collections.Generic
Imports System.Runtime.InteropServices
Imports System.IO
Class MainWindow

    Public Shared VistaStartupFolder As String = "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup"
    'C:\Documents and Settings\All Users\Start Menu\Programs\Startup  XP
    'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup   window7
    Public Shared XpStartupFolder As String = "C:\Documents and Settings\All Users\Start Menu\Programs\Startup"
    Public Shared BigBroDesktopLauncherExe As String = "BigBroDesktopLauncher.exe"

    Private MyImages As New Dictionary(Of String, String)

    Private Sub Ellipse1_MouseLeftButtonUp(ByVal sender As System.Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles Ellipse1.MouseLeftButtonUp
        ' Me.Topmost = Not Topmost
    End Sub
    Enum serviceErrorStatus

        RunningOK = 0
        SSNotRunning = 1
        RecServiceNotRunning = 2


    End Enum

    Dim _adapterPcInfo As DataSet1TableAdapters.workstationInfoTableAdapter
    Public ReadOnly Property AdapterPcInfo() As DataSet1TableAdapters.workstationInfoTableAdapter
        Get
            If _adapterPcInfo Is Nothing Then
                _adapterPcInfo = New DataSet1TableAdapters.workstationInfoTableAdapter
            End If
            Return _adapterPcInfo
        End Get
    End Property

    Dim WithEvents _timer As System.Windows.Threading.DispatcherTimer
    Dim _currentUser As String

    Private Sub MainWindow_Initialized(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Initialized
        Dim currentUser = Environment.UserName

        If Not (String.IsNullOrEmpty(currentUser) OrElse currentUser.ToLower.IndexOf("admin") > 0 OrElse currentUser.ToLower.IndexOf("agent") > 0 OrElse currentUser.ToLower.IndexOf("unknown") > 0 OrElse currentUser.ToLower.IndexOf("system") > 0) Then
            AdapterPcInfo.UpdateQueryBBrunLogOnName(Now, currentUser)
        End If

    End Sub
    Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded

        '  //Set postion to right lower corner of the screen
        Me.Left = Forms.Screen.PrimaryScreen.Bounds.Width - Me.Width

        Me.Top = Forms.Screen.PrimaryScreen.Bounds.Height - Me.Height - 30

        Dim da As New Animation.DoubleAnimation
        da.From = 1
        da.To = 0

        da.Duration = New Duration(TimeSpan.FromSeconds(2))
        'da.AutoReverse = True
        da.RepeatBehavior = RepeatBehavior.Forever

        Ellipse1.BeginAnimation(Ellipse.OpacityProperty, da)


        _timer = New System.Windows.Threading.DispatcherTimer()


        _timer.Interval = TimeSpan.FromSeconds(30)
        _timer.Start()



        Label3.Content = "Workstation: " + Environment.MachineName
      

        _myStatus = Status.RunningOk

        '  = Split(Microsoft.VisualBasic.Command())



        Dim param = Environment.GetCommandLineArgs()

        If param.Length > 1 Then
            Label1.Content = param(1)

        Else
            Label1.Content = Environment.UserName

        End If

       

        _currentUser = Label1.Content
        'SynchTime()
        ' Label1.Content = _currentUser

        setImages()

    End Sub
    Sub setImages()
        MyImages.Add("ClockOk", "/BigBroDesktopLauncher;component/Resources/clock.png")
        MyImages.Add("ClockError", "/BigBroDesktopLauncher;component/Resources/clock_error.png")

        ' ImageClock.Source = New BitmapImage(New Uri(MyImages("ClockOk"), UriKind.Relative))
    End Sub

    Dim IsActivated As Boolean
    Private Sub _timer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles _timer.Tick


        'Label1.Content = "enter time"

        If IsActivated = False Then

            Dim myp = Process.GetCurrentProcess

            If IsAlreadyRunning(myp.ProcessName) > 1 Then
                'MsgBox("I will now close")
                Me.Close()
            End If
            IsActivated = True
            'do regular task here
            DoWork()

            _timer.Interval = TimeSpan.FromMinutes(1)
        Else 'do regular process here
            ' Label3.Content = Now.Millisecond.ToString()
            DoWork()
        End If





    End Sub



    Enum Status
        RunningOk = 0
        ScreenshotNotRunning = 1

    End Enum

    Dim _myStatus As Status
    Shared minuteCnt As Integer

    Dim hasError As Boolean



    Sub DoWork()

        hasError = False


        Try
            AdapterPcInfo.UpdateQueryBBLauncherdate(Now)

            Dim u As String

            Dim itable As New DataSet1.workstationInfoDataTable
            itable = AdapterPcInfo.GetData()
            If itable.Rows.Count > 0 Then
                Dim irow As DataSet1.workstationInfoRow
                irow = itable(0)

                'Dim u = AdapterPcInfo.ScalarQueryCurrentUser()

                If Not irow.IsDateServiceRunningNull Then
                    Dim svcRun As DateTime = irow.DateServiceRunning

                    If svcRun.AddMinutes(3) > Now Then
                        u = irow.CurrentUser
                        If Not String.IsNullOrEmpty(u) Then
                            _currentUser = u
                        End If
                    End If
                End If
            End If

            If String.IsNullOrEmpty(u) Then
                _currentUser = MyCorrectionUser
            End If

        Catch ex As Exception
            _currentUser = MyCorrectionUser

        End Try



        minuteCnt += 1

        If System.IO.File.Exists(BigBroDesktopLauncher.MainWindow.VistaStartupFolder + "\" + BigBroDesktopLauncher.MainWindow.BigBroDesktopLauncherExe) Then 'running vista

            Dim i = IsAlreadyRunning("BigBroStartCapture")

            If i = 0 Then

                Try
                    'Dim dirExe As New DirectoryInfo(My.Application.Info.DirectoryPath + "\BigBroDesktopLauncher")   '.exe")
                    'If Not dirExe.Exists Then
                    '    dirExe.Create()
                    'End If

                    'Dim myexe As New FileInfo(My.Application.Info.DirectoryPath + "\BigBroStartCapture.exe")

                    'myexe.CopyTo(dirExe.FullName + "\BigBroStartCapture.exe")

                    'Dim myRoot As New Directory(My.Application.Info.DirectoryPath
                    Dim pInfo As ProcessStartInfo = New ProcessStartInfo("C:\Program Files\Justflowers PhilDev\JfWinSvcClient\BigBroStartCapture.exe")
                    'pInfo.CreateNoWindow = True
                    pInfo.WindowStyle = ProcessWindowStyle.Hidden
                    Process.Start(pInfo)
                    _myStatus = Status.RunningOk




                Catch ex As Exception
                    _myStatus = Status.ScreenshotNotRunning

                End Try

            End If



        Else ' running XP

        End If


        queryServerService("query", _servicenameScreenShot)
        ' writeLog("Service Status..." + _ServiceStatus)
        If _ServiceStatus = "STOPPED" Then
            'writeLog("Trying to start SERVICE..." + _servicename)
            'queryServerService("start")
            'Me.Ellipse1.Fill = Brushes.Yellow
            Label1.Content = _currentUser
            ImageSS.Width = 18
            hasError = True
            '_currentUser = Environment.UserDomainName

        Else
            ' Me.Ellipse1.Fill = Brushes.Red
            ImageSS.Width = 0
        End If

        queryServerService("query", _serviceNameRec)
        ' writeLog("Service Status..." + _ServiceStatus)
        If _ServiceStatus = "STOPPED" Then
            'writeLog("Trying to start SERVICE..." + _servicename)
            'queryServerService("start")

            Label1.Content = _currentUser
            Me.ImageRec.Width = 18
            hasError = True
        Else

            Me.ImageRec.Width = 0
        End If

        Try
            Dim service As New Cesb1WebReference.WebService

            If service.IsAlive Then
                Dim serverTime As DateTime = service.GetServerTime

                Dim i = Math.Abs(DateDiff(DateInterval.Minute, serverTime, Now.ToUniversalTime))
                ' Dim strUri2 As String = "/BigBroDesktopLauncher;component/Resources/clock_error.png"  'String.Format("//pack:/application:,,,/MyAseemby;component/resources/main titles/{0}", CurrenSelection.TitleImage);
                'imgTitle.Source = new BitmapImage(new Uri(strUri2));

                '           Uri src = new Uri(@"/ComponentName;component/Images/logo.png", UriKind.Relative);
                'BitmapImage img = new BitmapImage(src);
                'imgCurentLogo.Source = img;


                If i > 1 Then

                    'ImageClock.Source = New BitmapImage(New Uri(MyImages("ClockError"), UriKind.Relative))
                    ' ImageClock.Visibility = Windows.Visibility.Visible
                    ImageClock.Width = 18
                    hasError = True
                Else
                    'ImageClock.Source = New BitmapImage(New Uri(MyImages("ClockOk"), UriKind.Relative))
                    'ImageClock.Source = New BitmapImage(New Uri(MyImages("ClockOk"), UriKind.Relative))
                    ' ImageClock.Visibility = Windows.Visibility.Hidden
                    ImageClock.Width = 0
                End If

                ' ImageClock.Stretch = Stretch.Uniform
            End If
        Catch ex As Exception



        End Try




        If hasError Then
            Me.Ellipse1.Fill = Brushes.Yellow
            Me.Topmost = Not Me.Topmost
           


        Else
            Me.Ellipse1.Fill = Brushes.Red
            Me.Topmost = False

            Label1.Foreground = Brushes.Red
            Label1.Content = _currentUser 'Environment.UserName

        End If

        If Topmost Then
            Label1.Foreground = Brushes.Yellow
            Label1.Content = "WARNING WARNING"

        End If




    End Sub

    Dim _ServiceStatus As String
    'Dim _ip As String
    Dim _servicenameScreenShot As String = "JfClientService1"
    Dim _serviceNameRec As String = "JFRecordWatcher"

    Function queryServerService(ByVal cmdStr As String, ByVal service As String) As String
        'Dim arg = "sc \\10.22.22.206 " + cmdStr + " Service_jFabs"

        _ServiceStatus = "STOPPED"

        'Dim arg = "sc " + _ip + " " + cmdStr + " " + _servicename

        Dim arg = "sc " + cmdStr + " " + service


        'Dim arg = "sc \\10.22.22.206" + " start Service_jFabs"query
        Dim res = executeCmd(arg)
        'Dim ret As String

        Console.WriteLine(res)

        Dim mysplit = CmdSummaryResult(res)
        Dim keyworkStateFound As Boolean = False

        For Each i In mysplit

            If i.ToUpper = "STATE" Then
                keyworkStateFound = True
                Continue For
            End If

            If keyworkStateFound Then
                If i.ToUpper = "RUNNING" Then
                    _ServiceStatus = i
                    Exit For
                    'ElseIf String.IsNullOrEmpty(_ServiceStatus) Then
                ElseIf i.ToUpper = "STOPPED" Then
                    _ServiceStatus = i '"RUNNING"
                    Exit For
                End If
            End If

        Next

        Return _ServiceStatus


    End Function

    Function CmdSummaryResult(ByVal res As String) As String()
        Dim mysplit = res.Split()
        Dim result As New List(Of String)
        Dim int As Integer = -1

        For Each i In mysplit
            If String.IsNullOrEmpty(i) OrElse i.Length < 4 Then
                Continue For

            Else
                int += 1
                '  Me.RichTextBox1.AppendText(vbCrLf + int.ToString + "(" + i + ")")
                result.Add(i)

            End If
        Next


        Return result.ToArray

    End Function

    Function executeCmd(ByVal arguments As String, Optional ByVal RedirectStandardOutput As Boolean = True) As String


        Dim _info As ProcessStartInfo = New ProcessStartInfo("cmd", "/C " + arguments)

        _info.RedirectStandardOutput = RedirectStandardOutput
        _info.CreateNoWindow = True
        _info.UseShellExecute = False



        Dim _p As New Process
        _p.StartInfo = _info
        _p.Start()

        Dim _result As String = String.Empty
        If RedirectStandardOutput Then
            _result = _p.StandardOutput.ReadToEnd

            _p.Close()

        End If

        Return _result

    End Function


    Private Function IsAlreadyRunning(ByVal thisProcessname As String) As Integer



        '  Label1.Content = myp.ProcessName


        Dim list = Process.GetProcesses

        Dim q = From p In list _
                Where p.ProcessName = thisProcessname _
                Select p


        Return q.ToList.Count

    End Function

    Public Structure SYSTEMTIME
        Public wYear As UInt16
        Public wMonth As UInt16
        Public wDayOfWeek As UInt16
        Public wDay As UInt16
        Public wHour As UInt16
        Public wMinute As UInt16
        Public wSecond As UInt16
        Public wMilliseconds As UInt16
    End Structure

    Private Declare Function SetSystemTime Lib "kernel32" (ByRef lpSystemTime As SYSTEMTIME) As Boolean
    Private Declare Sub GetSystemTime Lib "kernel32" Alias "GetSystemTime" (ByRef lpSystemTime As SYSTEMTIME)


    Dim isSynch As Boolean

    Sub SynchTime()

        'tzone = "US Mountain Standard Time"  'or whatever your timezone is
        'Shell("CONTROL.EXE TIMEDATE.CPL,,/Z " & tzone)
        ' MsgBox("test")

        writeLog("start sych")

        Dim service As New Cesb1WebReference.WebService

        If service.IsAlive Then

            Dim serverTime As DateTime = service.GetServerTime

            Dim st As New SYSTEMTIME

            With st
                .wYear = serverTime.Year ' 1981
                .wMonth = serverTime.Month ' 1
                .wDayOfWeek = serverTime.DayOfWeek
                .wDay = serverTime.Day ' 1
                .wHour = serverTime.Hour ' 1
                .wMinute = serverTime.Minute ' 1

                .wSecond = serverTime.Second ' 0
                .wMilliseconds = serverTime.Millisecond
            End With
            If SetSystemTime(st) = True Then
                '  MessageBox.Show("System Time Changed")
                ImageClock.Visibility = Visibility.Hidden
                'isSynch = True
                'Else
                'MessageBox.Show(Marshal.GetLastWin32Error.ToString)
                'ImageClock.Visibility = Visibility.Visible
                'isSynch = False
            End If


            Dim sTimeZone As String = "Pacific Standard Time"

            Dim process As New Process()

            process.StartInfo.FileName = "control.exe"

            process.StartInfo.Arguments = "TIMEDATE.CPL,,/Z " & sTimeZone

            process.Start()

            Dim i = Math.Abs(DateDiff(DateInterval.Minute, serverTime, Now.ToUniversalTime))
            ' Dim strUri2 As String = "/BigBroDesktopLauncher;component/Resources/clock_error.png"  'String.Format("//pack:/application:,,,/MyAseemby;component/resources/main titles/{0}", CurrenSelection.TitleImage);
            'imgTitle.Source = new BitmapImage(new Uri(strUri2));

            '           Uri src = new Uri(@"/ComponentName;component/Images/logo.png", UriKind.Relative);
            'BitmapImage img = new BitmapImage(src);
            'imgCurentLogo.Source = img;


            If i > 1 Then

                'ImageClock.Source = New BitmapImage(New Uri(MyImages("ClockError"), UriKind.Relative))
                ' ImageClock.Visibility = Windows.Visibility.Visible
                ImageClock.Width = 18
                hasError = True
            Else
                'ImageClock.Source = New BitmapImage(New Uri(MyImages("ClockOk"), UriKind.Relative))
                'ImageClock.Source = New BitmapImage(New Uri(MyImages("ClockOk"), UriKind.Relative))
                ' ImageClock.Visibility = Windows.Visibility.Hidden
                ImageClock.Width = 0
            End If

            ImageClock.Stretch = Stretch.Uniform
        End If


        'Me.Ellipse1.Fill = Brushes.Blue





    End Sub

    Public Shared mylog As String = "C:\Program Files\Justflowers PhilDev\JfWinSvcClient\jfabsSVClog.txt"
    Private Sub writeLog(ByVal message As String, Optional ByVal Append As Boolean = True)
        Dim IsUpdateNow As Boolean = False

        SyncLock Me
            Dim f As New FileInfo(mylog)
            Try
                If f.Length > 200000 Then
                    Append = False
                End If

                My.Computer.FileSystem.WriteAllText(mylog, vbCrLf + Now.ToString + "LAUNCHER ***" + message, Append)



            Catch ex As Exception

                IsUpdateNow = True

            End Try
        End SyncLock

        'If IsUpdateNow Then
        '    If MyAutoUpdate.AutoUpdate(CommandLine, RemotePath) Then
        '        'Dispose()
        '        'Me.() 'Application.Exit()
        '        writeLog(" New Update... Installing")

        '        Me.Stop()
        '    End If

        'End If



    End Sub

  

    Private Sub ImageClock_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Input.MouseButtonEventArgs) Handles ImageClock.MouseUp
        '  SynchTime()
    End Sub


    Public ReadOnly Property MyCorrectionUser() As String
        Get

            Dim res As String = String.Empty


            Try

                Dim TimReports = From p In System.Diagnostics.Process.GetProcessesByName("TimeReport") _
                              Select p.StartInfo.UserName

                If TimReports.Count > 0 Then

                    res = TimReports(0)

                End If



                If String.IsNullOrEmpty(res) Then
                    'try another approach to find user
                    Dim iexplore = From p In System.Diagnostics.Process.GetProcessesByName("iexplore") _
                                Select p.StartInfo.UserName

                    If iexplore.Count = 0 Then
                        Dim explorer = From p In System.Diagnostics.Process.GetProcessesByName("explorer") _
                                               Select p.StartInfo.UserName
                        If explorer.Count = 0 Then

                            Dim firefox = From p In System.Diagnostics.Process.GetProcessesByName("firefox") _
                                              Select p.StartInfo.UserName
                            If firefox.Count = 0 Then
                                res = My.User.Name

                            Else
                                res = firefox.ToList(0)


                            End If


                        Else
                            res = explorer.ToList(0)


                        End If




                    Else 'interet

                        res = iexplore.ToList(0)

                    End If


                End If


                'Dim myDir = New DirectoryInfo(System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData)) '.SystemDirectory.ToString()))

                'Dim dir = New System.IO.DirectoryInfo(myDir.Parent.FullName)

                'Dim myList = From folder In dir.Parent.GetDirectories()
                '             Where folder.Name <> "All Users"
                '             Order By folder.LastWriteTime Descending
                '             Select folder.Name


                'res = myList.First



            Catch ex As Exception

            End Try

            'res = res.Replace(".CS", "")

            'If mySplit.Length > 0 Then
            '    res = mySplit(0)
            'End If

            Return res

        End Get
    End Property

End Class
